# file:: portal.rb
# author::  Ralph M. Churchill
# version::
# date::
#
# This source code copyright (C) 2006 by Ralph M. Churchill
# All rights reserved.
#
# Released under the terms of the GNU General Public License
# See LICENSE file for additional information.

require 'models/entity'
require 'models/container'
require 'models/describable_entity'

class Portal < Entity
    include ActsLikeLogicEntity,IsDescribable
    include BelongsToRegion
    properties :entries

    def initialize
        self.entries=[]
        super
    end

    alias_method :old_desc,:description
    def description
        old_desc.nil? ? self.name : old_desc
    end
    # Creates a portal entry from one room to another, given a direction,
    # specified by options. Valid options are:
    # [+from+] starting room
    # [+to+] ending room
    # [+direction+] direction from start to end
    def connect(opts={})
        raise Exception unless opts.key?(:from) and opts.key?(:to) and opts.key?(:direction)
        entry = PortalEntry.new
        entry.name = opts[:direction]
        entry.start_room = opts[:from]
        entry.end_room = opts[:to]

        entries << entry
    end

    # Creates a portal entry from one room to another, given a direction.
    # To, from are specified by options.
    # [+direction+] direction from start to end
    # Valid Options:
    # [+from+] starting room
    # [+to+] ending room
    def leads(direction,opts={})
        raise Exception unless opts.key?(:from) and opts.key?(:to)
        connect(:from => opts[:from],
                :to => opts[:to],
                :direction => direction)
    end
    # Alias for leads
    def goes(direction,opts={})
        leads(direction,opts)
    end
            

    # Makes a complete loop from *from* to *to and back.
    # [+from+] starting room
    # [+from_direction+] direction leading to ending room
    # [+to+] ending room
    # [+to_direction+] direction leading back to start
    def loop(from,from_direction,to,to_direction)
        connect(:from => from,
                :to => to,
                :direction => from_direction)
        connect(:from => to,
                :to => from,
                :direction => to_direction)
    end
        
end

class PortalEntry < Entity
    properties :start,:end

    def start_room=(room)
        raise "#{room} can't be a room!" unless room.respond_to?(:oid)
        @props ||= {}
        @props[:start_room_id] = room.oid
    end
    def start_room
        @props ||= {}
        RoomDatabase.instance.get(@props[:start_room_id])
    end
    def end_room=(room)
        raise "#{room} can't be a room!" unless room.respond_to?(:oid)
        @props ||= {}
        @props[:end_room_id] = room.oid
    end
    def end_room
        @props ||= {}
        RoomDatabase.instance.get(@props[:end_room_id])
    end
end
